<?php

require('config.php');
require("WoWCharacterParser.php");
require("SigGenerator.php");
require("readStats.php");
require('custom_stats.php');

$char = new WoWCharacterParser();
$sig = new SigGenerator();
$statReader = new StatReader();

$clean = array();
$stats = array();

/* zone/region validation */
if (isset($_GET['z']) && $_GET['z'] == 'eu') {
	$clean['zone'] = 'eu';
} else {
	$clean['zone'] = 'us';
}

/* realm name validation */
if (isset($_GET['r'])) {
	if (preg_match("/^[A-Za-z0-9\\\' -]+$/", $_GET['r'])) {
		$realm = ucwords(strtolower($_GET['r']));
		$realm = trim($realm);
		$realm = str_replace('\\\'', '\'', $realm);
		$realm = str_replace(' ', '+', $realm);
		$clean['realm'] = $realm;
	} else {
		$sig->createErrorSig('Invalid realm name');
	}
} else {
	$sig->createErrorSig('Missing realm name');
}

/* char name validation */
if (isset($_GET['n'])) {
	// check data, should be up to 12, ascii chars, auto format to first up
	if (strlen($_GET['n']) <= 12 && preg_match('/^[A-Za-z]{2,12}$/', $_GET['n'])) {
		$clean['name'] = ucfirst($_GET['n']);
	} else {
		$sig->createErrorSig('Invalid character name');
	}
} else {
	$sig->createErrorSig('Missing character name');
}

/* style validation */
if (isset($_GET['s'])) {
	if (is_numeric($_GET['s']) && $_GET['s'] > 0) {
		$clean['style'] = $_GET['s'];
	} else {
		$sig->createErrorSig('Invalid style');
	}
} else {
	$sig->createErrorSig('Missing style');
}

// check for cached images, outputs if found
//if ($sig->imageCache($clean['zone'], $clean['realm'], $clean['name'], 'pvp'.$clean['style'], 'none') == 0) {
	// if there is one, and up to date
//	exit;
//}

// get the data, from cache/blizzard
if ($char->loadData($clean['zone'], $clean['realm'], $clean['name']) > 0) { // failed
	$sig->createErrorSig('Failed to retrieve data. Please try again.');
}

// parse out the XML
$char->parseXML();

$full_profile = true;
// check for error messages here, or for missing data
if (count($char->character['page'][0]['children']['characterinfo'][0]['children']) == 0) {
	// error xml!1!, exit!
	$sig->createErrorSig('An error has occurred. Check spelling.');
} else if (count($char->character['page'][0]['children']['characterinfo'][0]['children']) == 1) {
	// if missing data, we want to write the cache only if no cache exists
	$char->writeCache($clean['zone'], $clean['realm'], $clean['name'], false); 
	// ideally here, we want to refresh more often than if we got real data!?
	$full_profile = false;
	// CHAR DATA AWAITING REFRESH!
} else {
	// plenty of data, overwrite cache!
	$char->writeCache($clean['zone'], $clean['realm'], $clean['name'], true);
	$full_profile = true;
}

$statReader->setCharObject($char);
// the required stats, that we always need to get!
$required = 'ABCDFGHL';

// grab all the required stats first
for ($i = 0; $i < strlen($required); $i++) {
	$stats[$custom_stats[$required[$i]]] = $statReader->getStat($custom_stats[$required[$i]]);
}

/* PVP Ratings */
$arenateams = $char->getArena();
$arena5rating = 'N/A';
$arena3rating = 'N/A';
$arena2rating = 'N/A';
if (count($arenateams) > 0) {
	foreach ($arenateams as $arenateam) {
		if ($arenateam['attr']['size'] == 5) {
			$arena5rating = $arenateam['attr']['rating'];
		} else if ($arenateam['attr']['size'] == 3) {
			$arena3rating = $arenateam['attr']['rating'];
		} else if ($arenateam['attr']['size'] == 2) {
			$arena2rating = $arenateam['attr']['rating'];
		}
	}
}

switch ($clean['style']) {
	case 2:
		$sig->overlayImage('assets/CurllSigBg2.jpg');
		break;
	case 3:
		$sig->overlayImage('assets/CurllSigBg3.jpg');
		break;
	default:
		$sig->overlayImage('assets/CurllSigBg1.jpg');
		break;
}
$sig->avatarImage('wow'.(($stats['Level']==70) ? '-70' : (($stats['Level'] < 60) ? '-default' : '')).'/'.$stats['Gender ID'].'-'.$stats['Race ID'].'-'.$stats['Class ID'].'.gif', 1, 1);
$sig->setFont('assets/fonts/verdanab.ttf');
$fontsize = 9;
//$sig->writeFont($fontsize, 70, 10, $title, 'white');
$sig->writeFont($fontsize, 70, 22, $stats['Name'].' <'.$stats['Guild'].'>', 'white');
$sig->writeFont($fontsize, 70, 37, 'HKs: '.$stats['HKs'], 'white');
$sig->writeFont($fontsize, 70, 52, $stats['Level'].' '.$stats['Class'], 'white');
// work out where the name/guild stops
$bbox = imagettfbbox($fontsize, 0, $sig->font, $stats['Name'].' <'.$stats['Guild'].'>');
$width = $bbox[4]-$bbox[6];
// check min/max bounds
$x = $width+70+20;
if ($x > 280) {
	$x = 280;
} else if ($x < 200) {
	$x = 200;
}
// place the ratings
$sig->writeFont($fontsize, $x, 22, '5v5 Rating: '.$arena5rating, 'white');
$sig->writeFont($fontsize, $x, 37, '3v3 Rating: '.$arena3rating, 'white');
$sig->writeFont($fontsize, $x, 52, '2v2 Rating: '.$arena2rating, 'white');

// store the sig in image cache
//$sig->writeCache($clean['zone'], $clean['realm'], $clean['name'], 'pvp'.$clean['style'], 'none');


$sig->output();

exit;

?>
